package com.huatai.common.util;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: ht-system
 * @description: 递归工具类
 * @author: songxiude
 * @create: 2023-02-17 17:03
 **/
public class TreeUtil {

	public static <T> T makeChildren(T t, List<T> list, String idName, String pidName,String childrenName){
		List<T> childList = new ArrayList<T>();
		for(int a = 0 ; a<list.size(); a++){
			String id = getFieldValueByClass(t,idName);
			String pid = getFieldValueByClass(list.get(a),pidName);
			if(StringUtils.isNotEmpty(pid) && pid.equals(id)){
				childList.add(makeChildren(list.get(a),list,idName,pidName,childrenName));
			}
		}
		setFieldValueByClass(t,childrenName,childList);
		return t;
	}
	/**
	 * 反射
	 * 属性取值
	 * @param t 实例
	 * @param field 取值字段
	 * @return
	 */
	public static <T> String getFieldValueByClass(T t, String field) {
		Class<?> aClass = t.getClass();
		try {
			Field f = aClass.getDeclaredField(field);
			f.setAccessible(true);
			return (String) f.get(t);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * 反射
	 * 对象属性赋值
	 * @param t 实例
	 * @param field 赋值的字段
	 * @param value 赋的值
	 * @return
	 */
	public static <T> void setFieldValueByClass(T t,String field,List<T> value) {
		Class<?> aClass = t.getClass();
		Field f = null;
		try {
			f = aClass.getDeclaredField(field);
			f.setAccessible(true);
			f.set(t, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
